<?php
ini_set('display_errors', 1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';
ini_set('memory_limit', '2048M');

use Doraemon\service\User;

$where['data_status'] = 1;
$where['ORDER'] = [
    'product_type' => 'ASC',
    'is_reserve' => 'DESC',
];

$list = \Biz\model\springHomeDecActivity\MSpringHomeDecWinningRecord::dataSelect($where);

$data = [];

$uids = array_column($list, 'uid');
$usersInfo = User::getBatchBasicUserInfo($uids);
$usersInfoMap = !empty($usersInfo) ? array_column($usersInfo, null, 'uid') : [];

$productIds = array_unique(array_column($list, 'product_id'));

$productMap = \Biz\service\springHomeDecActivity\WishListService::getProductsMap($productIds);

$productTypes = [1 => '商品', 2 => '服务'];
$isReserve = [0 => '未填写', 1 => '已填写'];

foreach ($list as $key => $item) {

    $address = '';

    if ($item['product_type'] == 1 && $item['is_reserve'] == 1 && $item['delivery_address'] != '|') {

        $Arr = explode('|', $item['delivery_address']);
        $lid = $Arr[0];
        $list[$key]['address'] = \Doraemon\tools\Area::locationId2String($lid);
        $address = $Arr[1];

    } else {
        $list[$key]['address'] = '';
    }

    $data[$key][0] = $usersInfoMap[$item['uid']]['nick'];
    $data[$key][1] = $item['uid'];
    $data[$key][2] = $productMap[$item['product_id']]['product_name'];
    $data[$key][3] = $productTypes[$item['product_type']];
    $data[$key][4] = $productMap[$item['product_id']]['product_value'];
    $data[$key][5] = $item['winning_date'];
    $data[$key][6] = $isReserve[$item['is_reserve']];
    $data[$key][7] = $item['name'];
    $data[$key][8] = $item['phone'];
    $data[$key][9] = $list[$key]['address'] . ' ' . $address;

}


$title = ['用户昵称', 'uid', '中奖商品', '奖品类型', '奖品价值', '中奖时间', '是否填写收货信息','收货人', '收货人电话', '收货地址'];

$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$titCol = 'A';
foreach ($title as $key => $value) {
    // 单元格内容写入
    $sheet->setCellValue($titCol . '1', $value);
    $titCol++;
}

$sheet->getColumnDimension('A')->setWidth(20);
$sheet->getColumnDimension('B')->setWidth(20);
$sheet->getColumnDimension('C')->setWidth(30);
$sheet->getColumnDimension('D')->setWidth(15);
$sheet->getColumnDimension('E')->setWidth(15);
$sheet->getColumnDimension('F')->setWidth(15);
$sheet->getColumnDimension('G')->setWidth(20);
$sheet->getColumnDimension('H')->setWidth(15);
$sheet->getColumnDimension('I')->setWidth(15);
$sheet->getColumnDimension('J')->setWidth(100);

$row = 2; // 从第二行开始
foreach ($data as $item) {
    $dataCol = 'A';
    foreach ($item as $value) {
        // 单元格内容写入
        $sheet->setCellValue($dataCol . $row, $value);
        $dataCol++;
    }
    $row++;
}

$fileName = date('Ymd', time()) . '.xlsx';

$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('./' . $fileName);